package cn.edu.cdut.service;

import cn.edu.cdut.dao.DownloadFileInfoDao;
import cn.edu.cdut.dao.MyScoreInfoDao;
import cn.edu.cdut.dao.PlanCourseInfoDao;
import cn.edu.cdut.dao.StudentInfoDao;
import cn.edu.cdut.dto.MyRes;
import cn.edu.cdut.model.DownloadFileInfo;
import cn.edu.cdut.model.PlanCourseInfo;
import cn.edu.cdut.model.ScoreInfo;
import cn.edu.cdut.model.StudentInfo;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.poi.ss.usermodel.Workbook;
import org.jeecgframework.poi.excel.ExcelExportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.Iterator;
import java.util.List;

/**
 * Author  kobe
 * Created on 2017-05-30-12:01
 */
@Service
public class ComputeScoreService {
        //@Autowired
        //private DisciplineInfoDao disciplineInfoDao;

        @Autowired
        private PlanCourseInfoDao planCourseInfoDao;

        @Autowired
        private MyScoreInfoDao myScoreInfoDao;

        @Autowired
        private StudentInfoDao studentInfoDao;

        @Autowired
        private DownloadFileInfoDao downloadFileInfoDao;

        //计算成绩
        @Transactional
        public void computeScore() throws IOException {

                String gradeID = null;//年级号
                String subjectID;//专业大类代号
                String classID;//班号
                String studentID;//学号

                Iterable<PlanCourseInfo> planCourseInfos = planCourseInfoDao.findAll();

                for (PlanCourseInfo planCourseInfo : planCourseInfos) {
                        gradeID = planCourseInfo.getGrade();
                        subjectID = planCourseInfo.getDisciplineId();
                        String courseStr = planCourseInfo.getCourses();
                        String[] courseArr = courseStr.split(",");
                        DecimalFormat decimalFormat = new DecimalFormat("#.0");
                        for (int i=1; ; i++) {
                                if (i < 10) {
                                        classID = gradeID+subjectID+"0"+i;
                                } else {
                                        classID = gradeID+subjectID+i;
                                }

                                if ( myScoreInfoDao.findByClassId(classID).size() != 0 ) {
                                        int stuNullCount = 0;
                                        //int stuNullIndex1 = 0;
                                        //int stuNullIndex2 = 0;
                                        for (int j=1; ; j++) {
                                                if (j < 10) {
                                                        studentID = classID+"0"+j;
                                                } else {
                                                        studentID = classID+j;
                                                }
                                                if (myScoreInfoDao.findByStuId(studentID).size() != 0) {
                                                        //计算一个学生成绩
                                                        double courseScore = 0;
                                                        for (String courseName : courseArr) {
                                                                List<ScoreInfo> scoreInfoList = myScoreInfoDao.findByStuIdAndCourse(studentID,courseName);
                                                                if (scoreInfoList.size() != 0) {
                                                                        if (scoreInfoList.size() == 1) {
                                                                                courseScore = courseScore + Double.parseDouble( scoreInfoList.get(0).getScore() );
                                                                        }else {
                                                                                //“正常成绩”与“补考”取高分
                                                                                double score1 = Double.parseDouble(scoreInfoList.get(0).getScore());
                                                                                double score2 = Double.parseDouble(scoreInfoList.get(1).getScore());
                                                                                if ( score1 <= score2 ) {
                                                                                        courseScore = courseScore + score2;
                                                                                }else {
                                                                                        courseScore = courseScore + score1;
                                                                                }
                                                                        }
                                                                }
                                                        }
                                                        double averageScore = Double.parseDouble(decimalFormat.format(courseScore/(courseArr.length)));
                                                        StudentInfo student = studentInfoDao.findByStuId(studentID);
                                                        if (student != null) {
                                                                student.setScore(averageScore);
                                                                studentInfoDao.save(student);
                                                        }
                                                }else {
                                                        stuNullCount++;
                                                        if (stuNullCount > 5 ) {
                                                                break;//表示此班级计算完毕
                                                        }
                                                }
                                        }
                                }else {
                                        break;//表示此大类计算完毕
                                }
                        }
                }

                //平均成绩Excel
                String scoreFileName = gradeID + "级大类学生平均成绩表.xls";

                File file1 = new File("src/main/resources/static/" + scoreFileName);
                if (file1.exists()) {
                        if (file1.delete()) {
                                //成绩表
                                List<StudentInfo> studentInfoList = studentInfoDao.findByGrade(gradeID);
                                Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(), StudentInfo.class, studentInfoList);
                                workbook.write(new FileOutputStream(new File("src/main/resources/static/"+scoreFileName)));
                        }
                } else if ( !file1.exists() ){
                        //文件信息
                        DownloadFileInfo downloadFileInfo = new DownloadFileInfo();
                        downloadFileInfo.setGradeId(gradeID);
                        downloadFileInfo.setFileName(scoreFileName);
                        downloadFileInfoDao.save(downloadFileInfo);
                        //成绩表
                        List<StudentInfo> studentInfoList = studentInfoDao.findByGrade(gradeID);
                        Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(), StudentInfo.class, studentInfoList);
                        workbook.write(new FileOutputStream(new File("src/main/resources/static/"+scoreFileName)));
                }
        }

        //获取所有成绩结果
        @Transactional
        public MyRes getAllStuScore() {

                //gradeID
                String gradeID = null;
                Iterable<PlanCourseInfo> planCourseInfos = planCourseInfoDao.findAll();
                Iterator<PlanCourseInfo> iterator = planCourseInfos.iterator();
                if (iterator.hasNext()) {
                        PlanCourseInfo planCourseInfo = iterator.next();
                        gradeID = planCourseInfo.getGrade();
                }
                //判断
                String scoreFileName = gradeID + "级大类学生平均成绩表.xls";

                File file2 = new File("src/main/resources/static/" + scoreFileName);
                if (file2.exists()) {
                        List<StudentInfo> studentInfos = studentInfoDao.findByGrade(gradeID);
                        ObjectMapper mapper = new ObjectMapper();
                        Iterator iter = studentInfos.iterator();
                        String[] resArr = new String[studentInfos.size()];
                        int i = 0;
                        while(iter.hasNext()){
                                try {
                                        resArr[i] = mapper.writeValueAsString(iter.next());
                                        i++;
                                } catch (JsonProcessingException e) {
                                        e.printStackTrace();
                                        return new MyRes(201, "获取学生成绩信息失败！", null);
                                }
                        }
                        return new MyRes(200, null, resArr);
                }else {
                        return new MyRes(200, null, null);
                }

        }

        //更新成绩
        @Transactional
        public MyRes updateScore(StudentInfo studentInfo) {
                studentInfoDao.save(studentInfo);
                return new MyRes(200, "提交成功！", null);
        }

        //获得单个成绩
        @Transactional
        public MyRes getStuScore(String stuId) {
                ObjectMapper mapper = new ObjectMapper();
                String res;
                try {
                        res = mapper.writeValueAsString(studentInfoDao.findByStuId(stuId));
                } catch (JsonProcessingException e) {
                        e.printStackTrace();
                        return new MyRes(201, "获取学生成绩信息失败！", null);
                }
                return new MyRes(200, null, res);
        }

}








